package com.zj.roseojcodesandbox.controller;

import com.zj.roseojcodesandbox.JavaNativeCodeSandbox;
import com.zj.roseojcodesandbox.model.ExecuteCodeRequest;
import com.zj.roseojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController("/")
public class MainController {

    /**
     * 请求头，用于判断请求用户是否有权限访问
     */
    public static final String AUTH_REQUEST_HEARTH = "auth";

    /**
     * 密钥
     */
    public static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    @GetMapping("/health")
    public String healthCheck(){
        return "ok";
    }

    /**
     * 执行代码，暴露接口给别人调用
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest,
                                    HttpServletRequest request, HttpServletResponse response){
        String header = request.getHeader(AUTH_REQUEST_HEARTH);
        if (!AUTH_REQUEST_SECRET.equals(header)){
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest ==null){
            throw new RuntimeException("请求参数为空");
        }
        return javaNativeCodeSandbox.executeCode(executeCodeRequest);
    }

}
